<template>
  <div class="w_h_100">
    <div class="box">
      <div class="inlet">系统管理 > 文件模版 > <span class="size">模版列表</span></div>
      <myform :fields="fields" :model="values" class="m_t_10" :options="options">
        <template v-slot:button>
          <el-button @click="resetting">重置</el-button>
          <el-button type="primary" :icon="Search" @click="searchFor">搜索</el-button>
        </template>
      </myform>
    </div>
    <div class="mytable m_t_10 ">
      <div class="d_f j_c_s_b a_i_c">
        <h4>模版列表</h4>
        <el-button type="primary" :icon="Plus" @click="addFile" v-hasPerm="'addFile'">新增模版</el-button>
      </div>
      <mytable :fields="tableFields" width="150" ref="tableRef" :values="values" api="fileListByPage" class="m_t_10"
        :isSelection="false">
        <template v-slot:deleted="{ row }">{{ row.deleted == 0 ? '已启用' : '已停用' }}</template>
        <template v-slot:operation="{ row }">
          <div class="d_f j_c_s_b">
            <span class="edit" @click="edit(row)" v-hasPerm="'editFile'">编辑</span>
            <span class="success" @click="modifyState(row.id, 0, '是否启用当前模版?')" v-if="row.deleted == 1" v-hasPerm="'statusFile'">启用</span>
            <span class="error" @click="modifyState(row.id, 1, '是否停用当前模版?')" v-else v-hasPerm="'statusFile'">停用</span>
          </div>
        </template>
      </mytable>
    </div>
    <el-drawer v-model="show" :title="title" size="500px" direction="rtl" :before-close="handleClose">
      <div class="myform">
        <myform :fields="addFields" :options="options" ref="ruleFrom" :model="model" :inline="false" labelPosition="top" :rules="rules"
          class="m_t_16">
        <template v-slot:url>
          <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    :action="action"
    multiple
    :on-remove="handleRemove"
    style="width: 100%;"
    :before-upload="beforeUpload"
    :on-success="onSuccess"
    :headers="headers"
    :on-exceed="onExceed"
    :limit="1"
  >
    <el-button type="primary">点击上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
        仅支持上传xls,xlsx,doc,docx格式
      </div>
    </template>
  </el-upload>
        </template>
        </myform>
      </div>
      <div class="d_f j_c_c">
        <el-button type="primary" @click="save" v-myRepeat>保存</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { fileType } from '../../../type/system'
import { copy, objectMatching,fileFormat} from '../../../utils/date'
import { ElMessageBox } from 'element-plus'
import { Message } from '../../../utils/resetMessage'
import {fileTemplateAdd,fileTemplateUpdate,fileTemplatePublish,dictDetail} from '../../../api/system/file'
import {httpConfig} from '../../../utils/config'
const values = {
  name: '',
  category: ''
}
const model = {
   id:0,
   name:'',
   category:'',
   url:'',
   remark:'',
}
export default defineComponent({
  name: '',
  setup() {
    const data: fileType = reactive({
      fields: [
        {
          label: "模版名称",
          prop: 'name',
          placeholder: '请输入',
          type: 'input',
          labelWidth:'70px'
        },
        {
          label: "模版分类",
          prop: 'category',
          placeholder: '请选择',
          type: 'select',
          bindLabel: 'name',
          bindValue: 'id',
        },
        {
          prop: 'button'
        }
      ],
      values: copy(values),
      options: {
        category: [],
      },
      tableFields: [
        {
          label: '模版名称',
          prop: 'name',
        },
        {
          label: '模版类型',
          prop: 'categoryName',
        },
        {
          label: '备注',
          prop: 'remark',
        },
        {
          label: '创建时间',
          prop: 'createdTime',
        },
      ],
      model: copy(model),
      rules: {
        name: [
          { required: true, message: '请输入模版名称', trigger: 'blur' },
        ],
        category: [
          { required: true, message: '请选择模版类型', trigger: 'blur' },
        ],
        url: [
          { required: true, message: '请上传文件', trigger: ['change','blur'] },
        ],
      },
      addFields: [
        {
          label: '模版名称',
          type: 'input',
          placeholder: '请输入',
          prop: 'name'
        },
        {
          label: '模版类型',
          prop: 'category',
          placeholder: '请选择',
          type: 'select',
          bindLabel: 'name',
          bindValue: 'id',
        },
        {
          prop: 'url',
          label: '文件'
        },
        {
          label: '备注',
          type: 'textarea',
          placeholder: '请输入',
          prop: 'remark',
          row: 5,
        }
      ],
      show: false,
      title: "新增模版",
      fileList:[],
      action:httpConfig.upload,
      headers:{
        token:localStorage.getItem('Token')
      }
    })
    onMounted(() => {
      methods.getDict()
    })
    const tableRef = ref()
    const ruleFrom = ref()
    const methods = {
      getDict(){
        
        dictDetail({ids:['FILE_TEMPLATE']}).then((res:any)=>{
            data.options.category=res.FILE_TEMPLATE
           
        })
      },
      //表格数据重置
      resetting() {
        data.values =  copy(values)
         tableRef.value.resettingTable(data.values)
      },
      //列表根据筛选条件搜索
      searchFor() {
        tableRef.value.handleCurrentChange(1)
      },
      //新增模版
      addFile() {
        data.title = '新增文件模版'
        data.show = true
      },
      edit(row: any) {
        data.title = '修改文件模版'
      data.model=objectMatching(row,data.model)
      data.model.category=row.categoryId
      data.fileList.push({name:row.url,url:row.url})
      data.show=true
      },
      //文件模版启用跟停用
      modifyState(id: number, status: number, val: string) {
        ElMessageBox.confirm(
          val,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            fileTemplatePublish({id:id,status:status}).then(()=>{
              Message({type:'success',message:'操作成功'})
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
            })
          })
      },
      //关闭弹窗
      handleClose() {
        ElMessageBox.confirm(
          '当前信息将不再保存?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            ruleFrom.value.resetFields()//重置表单
            data.show = false
            data.model = copy(model)
            data.fileList=[]
          })
      },
       //添加文件模版保存按钮事件
       save(){
        ruleFrom.value.verification().then(()=>{
          if(!data.model.id){
            fileTemplateAdd(data.model).then(()=>{
              Message({type:'success',message:'添加成功'})
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
              data.show=false//关闭弹窗
              ruleFrom.value.resetFields()//重置表单
              data.model=copy(model)//重置表单绑定数据
              data.fileList=[]
            })
          }else{
            fileTemplateUpdate(data.model).then(()=>{
              Message({type:'success',message:'修改成功'})
              tableRef.value.handleCurrentChange(1)//添加表格之后重新获取表格
              data.show=false//关闭弹窗
              ruleFrom.value.resetFields()//重置表单
              data.model=copy(model)//重置表单绑定数据
              data.fileList=[]
            })
          }
        })
      },
      //移除文件列表的事件
      handleRemove(){
        data.model.url=''
      },
      //文件上传之前校验格式
      beforeUpload(file:any){
       return fileFormat(file,['xlsx','xls','doc','docx'],'只能上传xlsx，xls')
      },
      //文件上传之后的事件
      onSuccess(src:any){
       if(src.code=='000000'){
        data.model.url=src.data
       }else{
        Message({type:'error',message:src.msg})
       }
      },
      onExceed(){
        Message({type:'error',message:'文件数量已超出限制，请先删除后上传'})
      }
    }
    return {
      ...toRefs(data),
      Search, Plus, ...methods,
      tableRef, ruleFrom
    }
  }
})
</script>
<style scoped lang='scss'>
.box {
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  height: 70px;
  padding: 10px 32px;
  margin-top: 10px;
}

.mytable {
  overflow-y: auto;
  width: calc(100% - 64px);
  background: #fff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px 32px;
  height: calc(100% - 125px);
}
</style>
<style lang="scss">
.myform {
  height: calc(100% - 70px);
  overflow-y: auto;
  .el-input,.el-select {
    width: 100% !important;
  }
}
</style>